<template>
  <div class="register-bg">
    <div class="register-card">
      <h2 class="register-title">用户注册</h2>
      <el-form :model="registerForm" :rules="rules" ref="registerForm" class="register-form">
        <el-form-item prop="studentId">
          <el-input v-model="registerForm.studentId" placeholder="学号" prefix-icon="el-icon-user" @blur="checkStudentId" />
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model="registerForm.phone" placeholder="手机号" prefix-icon="el-icon-phone" @blur="checkPhone" />
        </el-form-item>
        <el-form-item prop="nickname">
          <el-input v-model="registerForm.nickname" placeholder="昵称" prefix-icon="el-icon-user" @blur="checkNickname" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" placeholder="密码" prefix-icon="el-icon-lock" show-password />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" placeholder="确认密码" prefix-icon="el-icon-lock" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width:100%;font-size:18px;" @click="handleRegister">注册</el-button>
        </el-form-item>
      </el-form>
      <div class="register-footer">
        已有账号？<a href="#" style="color:#409EFF;" @click.prevent="$router.push('/login')">去登录</a>
      </div>
    </div>
  </div>
</template>

<script>
import UserService from '@/Services/UserService'

export default {
  name: 'RegisterView',
  data() {
    // 验证手机号
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!phoneRegex.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    // 验证学号
    const validateStudentId = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入学号'))
      } else if (!/^\d{8,12}$/.test(value)) {
        callback(new Error('学号格式不正确'))
      } else {
        callback()
      }
    }
    // 验证确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    return {
      registerForm: {
        studentId: '',
        phone: '',
        nickname: '',
        password: '',
        confirmPassword: ''
      },
      rules: {
        studentId: [
          { required: true, validator: validateStudentId, trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '昵称长度在2-20个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 检查学号是否已存在
    async checkStudentId() {
      if (this.registerForm.studentId) {
        try {
          const res = await UserService.CheckStudentId(this.registerForm.studentId)
          if (res.isSuccess && res.data) {
            this.$message.error('该学号已被注册')
            this.$refs.registerForm.fields.find(f => f.prop === 'studentId').validateState = 'error'
          }
        } catch (error) {
          console.error('检查学号错误：', error)
        }
      }
    },
    // 检查手机号是否已存在
    async checkPhone() {
      if (this.registerForm.phone) {
        try {
          const res = await UserService.CheckPhone(this.registerForm.phone)
          if (res.isSuccess && res.data) {
            this.$message.error('该手机号已被注册')
            this.$refs.registerForm.fields.find(f => f.prop === 'phone').validateState = 'error'
          }
        } catch (error) {
          console.error('检查手机号错误：', error)
        }
      }
    },
    // 检查昵称是否已存在
    async checkNickname() {
      if (this.registerForm.nickname) {
        try {
          const res = await UserService.CheckNickname(this.registerForm.nickname)
          if (res.isSuccess && res.data) {
            this.$message.error('该昵称已被使用')
            this.$refs.registerForm.fields.find(f => f.prop === 'nickname').validateState = 'error'
          }
        } catch (error) {
          console.error('检查昵称错误：', error)
        }
      }
    },
    async handleRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          try {
            const registerData = {
              studentId: this.registerForm.studentId,
              phone: this.registerForm.phone,
              nickname: this.registerForm.nickname,
              avatar: require('@/assets/Aatar/10001.jpg'),
              password: this.registerForm.password
            }
            const res = await UserService.Register(registerData)
            if (res.code === 200) {
              this.$message.success(res.message || '注册成功！')
              this.$router.push('/login')
            } else {
              this.$message.error(res.message || '注册失败')
            }
          } catch (error) {
            const errorMessage = error.response?.data?.message || '注册失败，请稍后重试'
            this.$message.error(errorMessage)
            console.error('注册错误：', error)
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.register-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #fffbe6 0%, #ffe100 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.register-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(0,0,0,0.10);
  padding: 48px 40px 32px 40px;
  width: 380px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.register-title {
  font-size: 28px;
  color: #222;
  margin-bottom: 32px;
  font-weight: bold;
  letter-spacing: 2px;
}
.register-form {
  width: 100%;
}
.register-footer {
  margin-top: 18px;
  color: #888;
  font-size: 15px;
  text-align: center;
}
</style> 